package zsc.liangyi.blog.service;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import zsc.liangyi.blog.model.domain.Article;
import zsc.liangyi.blog.model.domain.User;
import zsc.liangyi.blog.utils.EmailUtils;

import java.util.List;

@Service
public class RabbitMqService {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private UserService userService;
    @Autowired
    private EmailUtils eMailUtils;
    @Autowired
    private TemplateEngine templateEngine;

    @RabbitListener(bindings = @QueueBinding(value = @Queue("topic_queue_email"),
            exchange = @Exchange(value = "topic_exchange", type = "topic"),
            key = "info.#.email.#"
    ))
    @Async
    public void sendEMail(Message message) {
        String receiver = "";
        String subject = "博客热门排行";
        String emailContext = null;
        //thymeleaf的Context
        Context context = new Context();
        //获取文章热度信息
        List<Article> articleList_heat = articleService.getHeatArticle();
        context.setVariable("articleList_heat", articleList_heat);
        //获取全部注册用户，发送最新文章消息邮件
        List<User> userList = userService.getAllUser();
        for (User user : userList) {
            receiver = user.getEmail();
            context.setVariable("username", user.getUsername());
            emailContext = templateEngine.process("email/emailArticle", context);
            eMailUtils.sendEmail(receiver, subject, emailContext);
        }
    }

}

